﻿using System;
using System.Windows.Forms;
using Base;
using Core.Base;
using System.ComponentModel;
using System.Collections.Generic;
using Components;
using ERP.BusinessEntities.Base;
using ERP.DAL;
using System.Drawing;

namespace Core.Component
{
    public class SGVLookUpColumn : DataGridViewColumn, ISGVControl, IBindingControl
    {
        public BaseModule module;
        public BaseEntity entity;
        public SGVLookUpColumn()
            : base(new CustomTextBoxCell())
        {
        }

        public Core.Component.UIComponent component
        {
            set;
            get;
        }

        #region IBindingControl
        String _bindingPropertyName = "Text";

        String _bindingTable;
        String _bindingColumn;
        String _dataSourceTable;
        String _dataSourceDisplayColumn;
        String _dataSourceKeyColumn;
        String _dataSourceColumns;
        String _sGVShortcutString = "F2: DUYỆT DANH SÁCH";
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public String SGVShortcutString
        {
            get { return _sGVShortcutString; }
            set { _sGVShortcutString = value; }
        }
        String _sGVTag;
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string SGVTag
        {
            get
            {
                return _sGVTag;
            }
            set
            {
                _sGVTag = value;
            }
        }
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        string IBindingControl.BindingPropertyName
        {
            get
            {
                return _bindingPropertyName;
            }
            set
            {
                _bindingPropertyName = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string BindingTable
        {
            get
            {
                return _bindingTable;
            }
            set
            {
                _bindingTable = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string BindingColumn
        {
            get
            {
                return _bindingColumn;
            }
            set
            {
                _bindingColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceTable
        {
            get
            {
                return _dataSourceTable;
            }
            set
            {
                _dataSourceTable = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceDisplayColumn
        {
            get
            {
                return _dataSourceDisplayColumn;
            }
            set
            {
                _dataSourceDisplayColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceKeyColumn
        {
            get
            {
                return _dataSourceKeyColumn;
            }
            set
            {
                _dataSourceKeyColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public String DataSourceColumns
        {
            get
            {
                return _dataSourceColumns;
            }
            set
            {
                _dataSourceColumns = value;
            }
        }



        #endregion

        public void RegisterModule(Core.Base.BaseModule _module)
        {
            if (_module != null)
            {
                this.module = _module;
                this.entity = _module.entity;
            }
        }

        public void Init()
        {
            DestrucPropertyName();
            InitDataSource();
            this.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
            //this.DefaultCellStyle.Font = new System.Drawing.Font(this.DefaultCellStyle.Font.FontFamily, this.DefaultCellStyle.Font.Size, System.Drawing.FontStyle.Bold);
        }

        public virtual void InitDataSource()
        {
            try
            {

            }
            catch (Exception ex)
            {

            }


            //this.Columns
        }

        public void UpdateFormat()
        {
        }

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(CustomTextBoxCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }

        public void DestrucPropertyName()
        {

            if (String.IsNullOrEmpty(DataPropertyName)) return;
            String strColumnTag = DataPropertyName;
            DataPropertyName = String.Empty;

            String[] lstTags = strColumnTag.Split('|');

            if (lstTags.Length >= 1)
                DataPropertyName = lstTags[0];
            if (lstTags.Length >= 2)
                BindingTable = lstTags[1];
            if (lstTags.Length >= 3)
                DataSourceDisplayColumn = lstTags[2];
            if (lstTags.Length >= 4)
                DataSourceKeyColumn = lstTags[3];
            if (lstTags.Length >= 5)
                DataSourceTable = lstTags[4];
            if (lstTags.Length >= 6)
                DataSourceColumns = lstTags[5].Replace(',','|');

        }

        public UIComponent Serialize()
        {
            return null;
        }

        public void Deserialize(UIComponent component)
        {
            throw new NotImplementedException();
        }
    }

    public class CustomTextBoxCell : DataGridViewTextBoxCell
    {
        public CustomTextBoxCell()
            : base()
        {
            // Use the short date format.
            //this.Style.Format = "d";
        }

        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            //Size size = base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
            //try
            //{
            //    SGVCustomTextBoxColumn col = (SGVCustomTextBoxColumn)this.OwningColumn;
            //    BaseBusinessController ctrl = Host.GetCtrl(col.DataSourceTable);
            //    if (ctrl != null)
            //    {
            //        int iObjectID = Convert.ToInt32(this.Value);
            //        BaseBusinessInfo BusinessObj = (BaseBusinessInfo)ctrl.GetObjectById(iObjectID);
            //        if (BusinessObj != null)
            //        {
            //            Object objDisplay = AppContext.GetProperty(BusinessObj, col.DataSourceDisplayColumn);
            //            if (objDisplay != null)
            //                size = new Size(objDisplay.ToString().Length * 5, size.Height);

            //            // FormattedValue = String.Format(@"    {0}", objDisplay);

            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //}
            

            //return size;

            return base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
        }

        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                dataGridViewCellStyle);
            CustomTextBoxEditingControl ctl =
                DataGridView.EditingControl as CustomTextBoxEditingControl;

            ctl.BackColor = Color.Yellow;

            if (this.OwningColumn is SGVLookUpColumn)
            {
                SGVLookUpColumn col = (SGVLookUpColumn)this.OwningColumn;
                ctl.BindingColumn = col.DataPropertyName;
                ctl.BindingTable = col.BindingTable;
                ctl.DataSourceColumns = col.DataSourceColumns;
                if (String.IsNullOrEmpty(ctl.DataSourceColumns))
                {
                    ctl.DataSourceColumns = String.Format(@"No|Name|Dsc");
                }
                ctl.DataSourceDisplayColumn = col.DataSourceDisplayColumn;
                ctl.DataSourceKeyColumn = col.DataSourceKeyColumn;
                ctl.DataSourceTable = col.DataSourceTable;
            }
            ctl.Init();
            ctl.ID = Convert.ToInt32(this.Value);
            //ctl.Text = Convert.ToString(this.Value);
        }

        public override void DetachEditingControl()
        {
            base.DetachEditingControl();
            //CustomTextBoxEditingControl ctl =
            //    DataGridView.EditingControl as CustomTextBoxEditingControl;
            //ctl.ID = Convert.ToInt32(this.Value);
            //DataGridView.EditingPanel
        }

        public override object Clone()
        {
            CustomTextBoxCell TextBoxCell = base.Clone() as CustomTextBoxCell;
            if (TextBoxCell != null)
            {
                TextBoxCell.Tag = this.Tag;


            }
            return TextBoxCell; 
        }

        public override string ToString()
        {
            return base.ToString();
        }


        public override Type EditType
        {
            get
            {
                // Return the type of the editing contol that CalendarCell uses.
                return typeof(CustomTextBoxEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                // Return the type of the value that CalendarCell contains.
                return typeof(Int32);
            }
        }

        //protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        //{
        //    base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
        //}

        protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            formattedValue = String.Empty;
            
            try
            {
                SGVLookUpColumn col = (SGVLookUpColumn)this.OwningColumn;
                BaseBusinessController ctrl = Host.GetCtrl(col.DataSourceTable);
                if (ctrl != null)
                {
                    int iObjectID = Convert.ToInt32(value);
                    BaseBusinessInfo BusinessObj = (BaseBusinessInfo)ctrl.GetObjectById(iObjectID);
                    if (BusinessObj != null)
                    {
                        Object objDisplay = AppContext.GetProperty(BusinessObj, col.DataSourceDisplayColumn);
                        if (objDisplay != null)
                            //formattedValue = String.Format(@"    {0}", objDisplay);
                            formattedValue = objDisplay;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
            //graphics.DrawIcon(AppContext.DrillIcon, new Rectangle(cellBounds.X, cellBounds.Y, cellBounds.Height, cellBounds.Height));
        }

        public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
        {
            CustomTextBoxEditingControl ctl =
                DataGridView.EditingControl as CustomTextBoxEditingControl;
            return ctl.ID;
        }

        public override Type FormattedValueType
        {
            get
            {
                Type type =  base.FormattedValueType;
                return type;
            }
        }

        public override object DefaultNewRowValue
        {
            get
            {
                // Use the current date and time as the default value.
                return String.Empty;
            }
        }
    }

    class CustomTextBoxEditingControl : SGVTextBoxLookUp, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;

        public CustomTextBoxEditingControl()
        {
            this.CausesValidation = false;
        }


        public override void SetFocusAppreance()
        {
            //base.SetFocusAppreance();
        }

        public override void SetLostFocusAppreance()
        {
            //base.SetLostFocusAppreance();
        }

        //public override void Control_GotFocus(object sender, EventArgs e)
        //{
        //    //base.Control_GotFocus(sender, e);
        //    //LookUpButton.BackColor = this.BackColor;
        //}

        //public override void Control_LostFocus(object sender, EventArgs e)
        //{
        //    //base.Control_LostFocus(sender, e);
        //    //LookUpButton.BackColor = this.BackColor;
        //}
        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
               // return this.Value.ToShortDateString();
                return this.Text;
                //return "Hehehe";
            }
            set
            {
                if (value != null)
                {
                    //this.Value = DateTime.Parse((String)value);
                    this.Text = value.ToString();
                    //this.Text = "Hehehe";
                }
                else
                    this.Text = String.Empty;
            }
        }

        //public override object Par

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(
            DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            //this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            //this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return false;
            }
        }
         
        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        public override void OnIDChanged()
        {
            valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnIDChanged();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.A))
            {
                this.SelectAll();
            }
            else if (keyData == (Keys.Control | Keys.C))
            {
                this.Copy();
            }
            //else if (keyData == (Keys.Control | Keys.V))
            //{
            //    this.Paste();
            //}
            else if (keyData == (Keys.Control | Keys.X))
            {
                this.Cut();
            }
            else if (keyData == (Keys.Control | Keys.Z))
            {
                this.Undo();
            }
            else if (keyData == Keys.Enter)
            {
                //SendKeys.Send("{TAB}");
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        //protected override void OnTextChanged(EventArgs e)
        //{
        //     //Notify the DataGridView that the contents of the cell
        //     //have changed.
        //    valueChanged = true;
        //    this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        //    base.OnTextChanged(e);

        //}

        //protected override void OnValueChanged(EventArgs eventargs)
        //{
        //    // Notify the DataGridView that the contents of the cell
        //    // have changed.
        //    valueChanged = true;
        //    this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        //    //base.OnValueChanged(eventargs);
        //}
    }
}
